package cn.touna.jss.modules.custom.dataprocess;

import cn.touna.jss.common.aspect.ApiMappingCacheService;
import cn.touna.jss.common.aspect.entity.CacheCreditQueryRequest;
import cn.touna.jss.common.cache.HbaseComponent;
import cn.touna.jss.common.cache.dto.HbaseMapDto;
import cn.touna.jss.common.dict.CreditIntfConfCache;
import cn.touna.jss.common.dict.entity.IntfConfEntity;
import cn.touna.jss.common.properties.config.HbaseTableTopicProperties;
import cn.touna.jss.modules.credit.entity.CreditQueryHistoryEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.utils.JSONUtil;
import cn.touna.risk.data.hadoop.service.HbasePutService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * B001、B007数据补偿
 */
@Service
public class HistoryDataProcess {

    private static final Logger logger = LogManager.getLogger(HistoryDataProcess.class);

    @Autowired
    protected HbaseComponent hbaseComponent;
    @Autowired
    private HbasePutService hbasePutService;
    @Autowired
    private HbaseTableTopicProperties hbaseTableTopicProperties;
    @Autowired
    private CreditIntfConfCache creditIntfConfCache;
    @Autowired
    private ApiMappingCacheService apiMappingCacheService;
    /**
     * cr_query_history表
     */
//    @Autowired
//    private CreditQueryHistoryEntityMapper creditQueryHistoryEntityMapper;


 /**
     * 从cr_query_history表查询出需要补偿的数据
     * @return
     */
//    @Scheduled(cron = "0 25 16 * * ?")
    public void startProcess(){
        String dateArgs[] = {
            "20180601","20180602","20180603","20180604","20180605","20180606","20180607","20180608","20180609","20180610",
            "20180611","20180612","20180613","20180614","20180615","20180616","20180617","20180618","20180619","20180620",
            "20180621","20180622","20180623","20180624","20180625","20180626","20180627","20180628","20180629","20180630",
        };
        int argsLength = dateArgs.length;
        CreditQueryHistoryEntity entity = new CreditQueryHistoryEntity();
        //线程池，最大10个
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for(int i=0; i<argsLength; i++){
            String queryTime = dateArgs[i];
            entity.setQueryTime(queryTime);
//            List<CreditQueryHistoryEntity> list = creditQueryHistoryEntityMapper.queryList(entity);
            List<CreditQueryHistoryEntity> list = new ArrayList<>();
            logger.info("数据补偿开始,日期为为：{},数据量为：{}",queryTime,list.size());
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        queryMysqlData(list, queryTime);
                    } catch (Exception e) {
                        logger.info("线程池内执行异常");
                    }
                }
            });
        }
       logger.info("数据补偿逻辑处理完毕");
    }


    private void queryMysqlData(List<CreditQueryHistoryEntity> list, String queryTime){
        int cntSuc = 0;
        int cntFail = 0;
        logger.info("缓存查询开始,日期为：{},数据量为：{}",queryTime,list.size());
        for(CreditQueryHistoryEntity obj : list){
            if(StringUtils.isBlank(obj.getMethodName()) || StringUtils.isBlank(obj.getServiceName())){
                logger.info("这条数据有问题{}",obj.getCrNo());
                cntFail++;
                continue;
            }
            String apiUrl = obj.getServiceName()+"."+obj.getMethodName();
            CacheCreditQueryRequest request = new CacheCreditQueryRequest();
            request.setCrNo(obj.getCrNo());
            request.setBizType("B001");
            request.setQueryTime(obj.getTimeQuery());
            request.setServiceName(obj.getServiceName());
            request.setMethodName(obj.getMethodName());
            request.setMethod(apiUrl);
            request.setParams(JSONObject.parseObject(obj.getParams()));
            request.setIdCard(obj.getIdNo());
            request.setMobile(obj.getMobile());
            request.setClientIp("127.0.0.1");
            request.setCacheQueryAble("true");
            request.setExpiryDate(-1);
            IntfConfEntity intfConf = creditIntfConfCache.getExistInfConf(apiUrl);
            if(intfConf == null || StringUtils.isBlank(intfConf.getCacheStrategy())){
                logger.info("这条数据没有缓存策略{}",request);
                cntFail++;
                continue;
            }
            request.setCacheStrategy(intfConf.getCacheStrategy());
            // 查询缓存数据
            Response response = new Response();//apiMappingCacheService.queryDataFromCache(request);
            // 判断缓存数据是否为成功请求数据
            if (response.checkIfSuccess()) {
                response.setSrc(1);
                try{
                    this.saveCreditResult(request, response);
                    cntSuc ++;
                    logger.info("日期{},成功补偿第{}笔",queryTime,cntSuc);
                } catch (Exception e) {
                    logger.error("入Hbase失败{}",obj.getCrNo());
                    continue;
                }

            } else {
                cntFail++;
            }
        }
        logger.info("缓存查询结束,日期为：{},数据量为：{},成功{}笔,失败{}笔",queryTime,list.size(),cntSuc,cntFail);
    }

    public void saveCreditResult(CacheCreditQueryRequest request, Response response) {
        HbaseMapDto payloadDto = new HbaseMapDto();
        payloadDto.setTableName(hbaseTableTopicProperties.getCrsHistoryReport());
        String rowKey = "JSSBC"+request.getCrNo()+"."+request.getMethod();
        payloadDto.setRowKey(rowKey);
        logger.info("本次补偿的RowKey:{}",rowKey);
        CreditQueryHistoryEntity historyEntity = new CreditQueryHistoryEntity();
        historyEntity.setCrNo(request.getCrNo());
        historyEntity.setBizType(request.getBizType());
        historyEntity.setIdNo(request.getIdCard());
        historyEntity.setMobile(request.getMobile());
        historyEntity.setMethodName(request.getMethodName());
        historyEntity.setServiceName(request.getServiceName());
        historyEntity.setParams(request.getParams() == null ?"":JSONObject.toJSONString(request.getParams()));
        historyEntity.setSrc(1);
        historyEntity.setTimeQuery(request.getQueryTime());
        historyEntity.setResponseCode(response.getCode());
        historyEntity.setResponseMsg(response.getMsg());
        historyEntity.setTimeResponse(new Date());
        if (null != response.getData()) {
            historyEntity.setResponseData(JSON.toJSONString(response.getData()));
        }
        Map<String, Object> resultMap = JSONUtil.toMap(historyEntity);
        payloadDto.setHistory(resultMap);
        hbasePutService.put(payloadDto);
    }

}
